package com.boarsoft.flow.demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.boarsoft.common.util.JsonUtil;
import com.boarsoft.common.util.StreamUtil;
import com.boarsoft.flow.core.SimpleFlow;
import com.boarsoft.flow.core.SimpleFlowEngine;
import com.boarsoft.flow.demo.bean.User;

public class Main {
	private static Logger log = LoggerFactory.getLogger(Main.class);
	private static ClassPathXmlApplicationContext ctx;

	public static void main(String[] args) throws Exception {
		ctx = new ClassPathXmlApplicationContext("classpath:conf/context.xml");
		System.out.println("Startup ".concat(ctx.isRunning() ? "successfully." : "failed."));

		// try {
		// SimpleFlowEngine fe = (SimpleFlowEngine)
		// ctx.getBean("simpleFlowEngine");
		// traceTest(fe, 1, true);
		// traceTest(fe, 10, true);
		// } catch (Throwable e) {
		// log.error("Error on do test", e);
		// ctx.close();
		// System.exit(-1);
		// }

		SimpleFlowEngine fe = (SimpleFlowEngine) ctx.getBean("simpleFlowEngine");
		BufferedReader ir = null;
		String cmd = null;
		try {
			System.out.println("Say 'bye' to exit");
			ir = new BufferedReader(new InputStreamReader(System.in));
			while ((cmd = ir.readLine()) != null) {
				try {
					traceTest(fe, 1, true);
				} catch (Throwable e) {
					log.error("Error on call traceTest", e);
				}
				if ("bye".equalsIgnoreCase(cmd)) {
					break;
				}
			}
		} catch (Throwable e) {
			log.error("Error on running", e);
		} finally {
			StreamUtil.close(ir);
		}
		System.out.println("bye");
		System.exit(0);
	}

	public static void traceTest(SimpleFlowEngine fe, int n, boolean push) throws Throwable {
		final User u = new User();
		u.setName("Mac_J");
		u.setPassword("123");

		for (int i = 0; i < n; i++) {
			SimpleFlow fo = fe.start("login", u);
			String json = JsonUtil.from(fo.getTrace());
			log.info("Flow trace {}:\n{}\n", fo.getId(), json);
		}
	}

	public static void basicTest1(SimpleFlowEngine fe) throws Throwable {
		User u = new User();
		u.setName("Mac_J");
		u.setPassword("123");
		SimpleFlow f1 = fe.start("login", u);
		log.info(JsonUtil.from(f1.getData()));

		// SimpleFlow f2 = fe.start("accountQry",
		// "00000000000000000000000000000000");
		// System.out.println(JsonUtil.from(f.getData()));

		Map<String, Object> pm = new HashMap<String, Object>();
		pm.put("userId", u.getId());
		pm.put("work", 3);
		SimpleFlow f3 = fe.start("makeMoney", pm);
		System.out.println(JsonUtil.from(f3.getData()));
		System.out.println(JsonUtil.from(f3.getTrace()));
	}
}
